package com.example.pan.ui.drive

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.pan.R
import com.example.pan.databinding.FragmentDriveBinding
import com.example.pan.model.BAIDU_DRIVE
import com.example.pan.model.Drive
import com.hi.dhl.binding.viewbind
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect

@AndroidEntryPoint
class DriveFragment : Fragment(R.layout.fragment_drive) {

    val binding by viewbind<FragmentDriveBinding>()
    private val mViewModel by viewModels<DriveViewModel>()
    private val adapter = DriveAdapter()

    @ExperimentalCoroutinesApi
    private val loginRequest =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == 200) {
                it.data?.getStringExtra("access_token")?.let { token ->
                    mViewModel.loginDrive(BAIDU_DRIVE, token)
                }
            } else {
                Toast.makeText(context, "登录失败,请重新登录", Toast.LENGTH_SHORT).show()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
        lifecycleScope.launchWhenCreated {
            mViewModel.drivePageSource.collect {
                adapter.submitData(it)
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initRecyclerView()
    }

    private fun initRecyclerView() = binding.apply {
        adapter.setOnClickListener(object : DriveAdapter.OnClickListener {
            override fun onItemClick(drive: Drive) {
                val action =
                    DriveFragmentDirections.actionNavigationDriveToNavigationDriveFile(drive.token)
                findNavController().navigate(action)
            }
        })
        adapter.addLoadStateListener {
            binding.refreshLayout.isRefreshing = it.refresh == LoadState.Loading
        }
        driveList.layoutManager = LinearLayoutManager(context)
        driveList.adapter = adapter
        driveList.itemAnimator = DefaultItemAnimator()
        driveList.addItemDecoration(
            DividerItemDecoration(
                context,
                DividerItemDecoration.VERTICAL
            )
        )
        refreshLayout.setOnRefreshListener {
            adapter.refresh()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.activity_main_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    @ExperimentalCoroutinesApi
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.menu_search) {
            Toast.makeText(context, "开始登录", Toast.LENGTH_SHORT).show()
            loginRequest.launch(Intent(context, LoginActivity::class.java))
        }
        return super.onOptionsItemSelected(item)
    }

}